﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using SchoolManagement.Utilities;

namespace SchoolManagement.Models.Authrization
{
    /// <summary>
    /// For Custom Authorization
    /// </summary>
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
       
        // the Roles property on the underlying class
        public new SiteRoles Roles;
        private bool FailedRolesAuth = false;

        /// <summary>
        /// Over ride the Authorize core method
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            string[] users = Users.Split(',');

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            User currentUser= httpContext.Session[Constants.User] as User;
            SiteRoles role = (SiteRoles)currentUser.UserRole;

            if (Roles != 0 && ((Roles & role) != role))
            {
                FailedRolesAuth = true;
                return false;
            }
            else
            {
                FailedRolesAuth = false;
            }

            return true;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (FailedRolesAuth)
            {
                filterContext.Result = new ViewResult { ViewName = "NotAuth" };
            }
        }
    }
   
}
